package edu.gatech.geochat;

import edu.gatech.geochat.database.Storage;
import edu.gatech.geochat.model.User;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class LoginActivity extends BetterActivity {

	public static void launch(Activity source) {
		Intent intent = new Intent(source, LoginActivity.class);
		source.startActivity(intent);
	}
	
	private TextView userView;
	private TextView passView;
	
	@Override
	public void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		setContentView(R.layout.login);
		
		userView = (TextView) findViewById(R.id.loginUser);
		passView = (TextView) findViewById(R.id.loginPass);
		
		setStatusText("");
	}
	

	@Override
	public void onPause() {
		super.onPause();
		GUISpace.put(getClass(), "username", userView.getText().toString());
		GUISpace.put(getClass(), "password", passView.getText().toString());
	}
	@Override
	public void onResume() {
		super.onPause();
		userView.setText(GUISpace.getString(getClass(), "username"));
		passView.setText(GUISpace.getString(getClass(), "password"));
	}
	
	public void register(View view) {
		RegisterActivity.launch(this, userView.getText().toString(), passView.getText().toString());
	}
	
	private volatile boolean attemptingLogin = false;
	private synchronized void tryLogin(final String name, final String pass) {
		if (attemptingLogin) return;
		attemptingLogin = true;

		new Thread() {
			public void run() {
				String response = Storage.getInstance()
						.validateUser(name, pass);
				setStatusText(response);

				if (response == Storage.RESPONSE_SUCCESS) {
					User user = Storage.getInstance().getUser(name, pass);
					if (user == null) {
						setStatusText("Your credentials validated but the server returned null.");
					} else {
						TitleActivity.launch(LoginActivity.this, user);
					}
				}
				attemptingLogin = false;
			}
		}.start();
	}
	
	public void login(View view) {
		if (attemptingLogin) 
			return;
		
		String uname = userView.getText().toString().trim();
		String upass = passView.getText().toString().trim();
		if (uname.length() == 0) {
			setStatusText("Please enter your username.");
			return;
		}
		if (upass.length() == 0) {
			setStatusText("Please enter your password.");
			return;
		}
		if (uname.length() > 0 && upass.length() > 0) {
			setStatusText("Checking credentials with server...");
			tryLogin(uname, upass);
		}
	}
}
